package com.yoso.shop.application.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.yoso.base.service.BaseService;
import com.yoso.shop.application.service.IConsumerService;
import com.yoso.shop.domain.user.ConsumerEntity;
import com.yoso.shop.domain.user.ConsumerEntityExample;
import com.yoso.shop.infrastructure.dao.user.ConsumerEntityMapper;
import com.yoso.shop.infrastructure.factory.ShopBeanFactory;
import com.yoso.shop.interfaces.vo.user.ConsumerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author shizejin
 * @date 2021/11/17
 * @description:
 */
@Service
public class ConsumerServiceImpl extends BaseService<ConsumerEntity, ConsumerVo, ConsumerEntityExample> implements IConsumerService {
    @Autowired
    private ConsumerEntityMapper consumerEntityMapper;
    @Override
    public ConsumerEntity V2E(ConsumerVo data) {
        return JSON.parseObject(JSON.toJSONString(data),ConsumerEntity.class);
    }

    @Override
    public ConsumerVo E2V(ConsumerEntity data) {
        return JSON.parseObject(JSON.toJSONString(data),ConsumerVo.class);

    }

    @Override
    public ConsumerEntityExample getEntityExample(Map<String,String> paramMap) {
        return new ConsumerEntityExample();
    }

    /**
     * 用户注册
     */
    @Override
    public boolean register(ConsumerVo consumerVo) {
        ConsumerEntityExample example = new ConsumerEntityExample();
        example.createCriteria()
                .andUsernameEqualTo(consumerVo.getUsername());
        List<ConsumerVo> voList = this.selectByExample(example);

        boolean result = CollectionUtils.isEmpty(voList);
        if (result) {
            this.insertSelective(ShopBeanFactory.initConsumerVo(consumerVo));
        }
        return result;
    }

    /**
     * 用户登录
     */
    @Override
    public ConsumerVo login(ConsumerVo consumerVo) {
        consumerVo = ShopBeanFactory.initConsumerVo(consumerVo);
        ConsumerEntityExample example = new ConsumerEntityExample();
        example.createCriteria()
                .andUsernameEqualTo(consumerVo.getUsername())
                .andPasswordEqualTo(consumerVo.getPassword());
        List<ConsumerVo> result = this.selectByExample(example);
        if (CollectionUtils.isEmpty(result)){
            return null;
        }
        return result.get(0);
    }

    /**
     * 根据注册账号查询（username）
     *
     */
    @Override
    public ConsumerVo findByUsername(String username) {
        ConsumerEntityExample example = new ConsumerEntityExample();
        example.createCriteria()
                .andUsernameEqualTo(username);
        List<ConsumerVo> list = this.selectByExample(example);
        if (CollUtil.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }
}
